#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "service.h"
#include "utils.h"
#include "MCP23017.h"
#include "crc.h"

osEventFlagsId_t service_EvtID;
osThreadAttr_t service_Attr;

int service_ReadUartLength;
int service_UartLength;

uint8_t service_uartData[300];
uint8_t * service_uartDataPtr;

uint8_t service_sendUartData[100];
uint8_t * service_sendUartDataPtr;

void Service_sendOSEvent(void){
    osEventFlagsSet(service_EvtID, SERVICE_FLAGS_MSK1);
    osThreadYield();
}

// 业务处理线程
static void * service_Task(const char *arg){
    (void)arg;

    mm_LogPrint("[HMNetDTU]NetDTU service Task start....\r\n");

    while(1){
        osEventFlagsClear(service_EvtID,SERVICE_FLAGS_MSK1);
        osEventFlagsWait(service_EvtID, SERVICE_FLAGS_MSK1, osFlagsWaitAny, 500);
        if(service_ReadUartLength != 0){
            service_UartLength = service_ReadUartLength;
            service_ReadUartLength = 0;
            mm_LogPrint("[HMDTU_service]uart2 get Data length:%d\r\n",service_UartLength);

            if(service_uartData[0] == 0x02 && service_uartData[1] == 0x03 && service_uartData[3] == 0x0A){            // 1号地址读IO
                uint8 readBack = MCP23017_READ_GPIO(0x00,MCP23017_PORTA);

                service_sendUartData[0] = 0x02;
                service_sendUartData[1] = 0x03;
                service_sendUartData[2] = 0x02;
                service_sendUartData[3] = 0x00;
                service_sendUartData[4] = readBack;

                service_sendUartData[5] = ModbusCRC(service_sendUartData, 5) >> 8;
				service_sendUartData[6] = ModbusCRC(service_sendUartData, 5) & 0xFF;


                ModbusCRC(service_sendUartDataPtr, 5);

                IoTUartWrite(2, service_sendUartDataPtr, 7);
            }else if(service_uartData[0] == 0x03 && service_uartData[1] == 0x06 && service_uartData[3] == 0x0A){
                MCP23017_WRITE_GPIO(0x00,MCP23017_PORTB,service_uartData[5]);
                IoTUartWrite(2, service_uartDataPtr, service_UartLength);
            }else{

            }
        }
        
        memset(service_sendUartData,0,100);
        memset(service_uartData,0,300);
    }

    return NULL;
}

void service_init(void){
    service_Attr.name = "service_Task";
    service_Attr.attr_bits = 0U;
    service_Attr.cb_mem = NULL;
    service_Attr.cb_size = 0U;
    service_Attr.stack_mem = NULL;
    service_Attr.stack_size = 1024 * 20;
    service_Attr.priority = 25;


    service_uartDataPtr = service_uartData;
    service_sendUartDataPtr = service_sendUartData;

    if (osThreadNew((osThreadFunc_t)service_Task, NULL, &service_Attr) == NULL) {
        mm_LogPrint("[HMNetDTU] Falied to create service_Task!\n");
    }
    service_ReadUartLength = 0;
    service_EvtID = osEventFlagsNew(NULL);
}